# coding=utf-8

from . import admin
from flask import request, render_template
from app import util
from dbConnection.MysqlConn import Mysql
from app.MySession import MySession


# 管理员列表
@admin.route('/admin/list.html', methods=['POST', 'GET'])
@util.admin_login
def admin_list_html():
    mysql = Mysql()
    sql = "select a.*,b.user_type_name from user_admin as a left join user_admin_type as b on b.id=a.user_type where a.user_type !=2"
    result = mysql.getAll(sql, None)
    mysql.dispose()
    data = []
    code = util.CODE_EMPTY
    if result:
        code = util.CODE_SUCCESS
        data = result
    res = {
        'data': data,
        'code': code
    }
    return render_template('admin/system/admin_list.html', res=res)


# 删除
@admin.route('/admin/manage/delete', methods=['POST', 'GET'])
@util.admin_login
def admin_manage_delete():
    uid = request.values.get('uid')
    mysql = Mysql()
    sql = "delete  from user_admin where uid='%s'" % uid
    res = mysql.delete(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


# 禁用
@admin.route('/admin/manage/stop', methods=['POST', 'GET'])
@util.admin_login
def admin_manage_stop():
    uid = request.values.get('uid')
    mysql = Mysql()
    sql = "update user_admin set status=0 where uid='%s'" % uid
    res = mysql.update(sql, None)
    mysql.dispose()
    print res
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


@admin.route('/admin/manage/start', methods=['POST', 'GET'])
@util.admin_login
def admin_manage_start():
    uid = request.values.get('uid')
    mysql = Mysql()
    sql = "update user_admin set status=1 where uid='%s'" % uid
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


@admin.route('/admin/manage/newly.html', methods=['POST', 'GET'])
@util.admin_login
def admin_mange_newly():
    if request.method == "GET":
        sql = 'select * from user_admin_type WHERE id != 1'
        mysql = Mysql()
        result = mysql.getAll(sql, None)
        mysql.dispose()
        return render_template('admin/system/admin_manage_newly.html', result=result)
    else:
        try:
            name = request.values.get('name')
            password = request.values.get('password')
            user_type = request.values.get('user_type')
            password = util.md5(str(password))
            mysql = Mysql()
            sql = "select * from user_admin where username='%s' " % name
            result = mysql.getOne(sql, None)
            code = util.CODE_EMPTY
            if result is None:
                add_sql = 'insert into user_admin (username,password,user_type, create_time) values ("%s","%s",%s' \
                          ',now())' % (name, password, user_type)
                result = mysql.insertOne(add_sql, None)
                if result:
                    code = util.CODE_SUCCESS
                    add_group = "insert into user_route_group (uid) VALUES ('%s')" % (result)
                    mysql.insertOne(add_group, None)
            mysql.dispose()
        except Exception as e:
            print e
            code = util.CODE_ERROR
        data = {
            'code': code
        }
        return util.to_json(data)


# 添加路由
@admin.route('/admin/route/newly.html', methods=['POST', 'GET'])
@util.admin_login
def admin_route_newly():
    if request.method == 'GET':
        return render_template('admin/system/admin_route_newly.html')
    else:
        try:
            route_name = request.values.get('route_name')
            route_url = request.values.get('route_url')

            mysql = Mysql()
            res = mysql.getOne("select * from user_route_url where route_url='%s'" % route_url, None)
            if res is None:
                sql = "insert into user_route_url(route_url,route_name)values('%s','%s')" % (route_url, route_name)
                result = mysql.insertOne(sql, None)
            mysql.dispose()
            code = util.CODE_EMPTY
            if result:
                code = util.CODE_SUCCESS
        except Exception as e:
            print e
            code = util.CODE_ERROR
        data = {
            'code': code
        }
        return util.to_json(data)


# 权限管理界面
@admin.route('/admin/manage/power.html', methods=['POST', 'GET'])
@util.admin_login
def admin_manage_power():
    uid = request.args.get('uid')
    mysql = Mysql()
    sql = "select uid,username from user_admin where uid='%s'" % uid
    result = mysql.getOne(sql, None)
    mysql.dispose()
    return render_template('admin/system/admin_manage_power.html', result=result)


# 查看用户权限，显示侧边栏
@admin.route('/admin/jurisdiction', methods=['POST', 'GET'])
@util.admin_login
def jurisdiction():
    session = request.cookies.get("uid")
    name = MySession.get_name(session)
    mysql = Mysql()
    data = {
        'status': "error"
    }
    sql = "select b.large,b.small from user_admin as a left join user_route_group as b on a.uid=b.uid where a.username='%s'" % name
    result = mysql.getOne(sql, None)
    if result:
        data['status'] = 'success'
        all_small = result['small']
        if all_small == 'all':
            data['status'] = 'all'
        else:
            data['small'] = all_small
            all_small = all_small.split(',')
            param = '('
            for index, uid in enumerate(all_small):
                if index < len(all_small):
                    param += str(uid)
                    if index < len(all_small) - 1:
                        param += ', '
            param += ')'
            if len(param) > 2:  # 判断用户是否有权限
                sql = "SELECT route_name,route_id FROM user_route_url WHERE route_id IN  %s " % param
                result = mysql.getAll(sql, None)
                data['arr'] = result
            else:
                data['status'] = 'empty'
    mysql.dispose()
    return util.to_json(data)


@admin.route('/admin/permission_data', methods=['POST'])
@util.admin_login
def permission_data():
    uid = request.values.get('uid')
    mysql = Mysql()
    sql = "select b.large,b.small from user_admin as a left join user_route_group as b on a.uid=b.uid where a.uid='%s'" % uid
    have = mysql.getOne(sql, None)
    data = {
        'status': 'fail'
    }
    if have is not None:
        all_id = str(have['small']).split(',')
        a = "("
        for r in all_id:
            a += "'" + r + "',"
        a = a[:-1]
        a += ")"
        a_sql = "SELECT route_name FROM user_route_url WHERE route_id IN %s " % a
        result = mysql.getAll(a_sql, None)
        if result is not None:
            data['status'] = 'success'
        data['arr'] = result
    mysql.dispose()
    return util.to_json(data)


# 根据路由对应的名称来保存权限
@admin.route('/admin/update_per', methods=['POST'])
@util.admin_login
def update_per():
    arr = request.values.get('arr')
    cur_id = request.values.get('cur_id')
    print cur_id
    data = {
        'status': 1
    }
    all_info = arr.split(',')
    a = "("
    for info in all_info:
        a += "'" + info + "',"
    a = a[:-1]
    a += ")"
    mysql = Mysql()
    sql = "SELECT route_id FROM user_route_url WHERE route_name IN %s " % a
    result = mysql.getAll(sql, None)
    all_id = ''
    if result is not None:
        for res in result:
            all_id += str(res['route_id']) + ","
        all_id = all_id[:-1]
    cur_sql = "UPDATE user_route_group set small = '%s' WHERE uid = %s " % (all_id, cur_id)
    mysql.update(cur_sql, None)
    mysql.dispose()
    return util.to_json(data)
